package com.david.videoapp.activity

import android.annotation.SuppressLint
import android.content.ContentUris
import android.content.res.Configuration
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.provider.MediaStore
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.updateLayoutParams
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.common.Player.Listener
import androidx.media3.exoplayer.DefaultRenderersFactory
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
import androidx.media3.ui.PlayerView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Adapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.david.core.utils.CommonUtils
import com.david.core.utils.TextPinyinUtil
import com.david.core.view.MySeekBar
import com.david.core.view.OnMySeekBarChangeListener
import com.david.videoapp.R
import com.david.videoapp.exoplayer.BlackListMediaCodecSelector
import java.util.Locale


class VideoListActivity : AppCompatActivity(), OnClickListener {
    private lateinit var playerView: PlayerView
    private var exoPlayer: ExoPlayer? = null


    private lateinit var statusBarBg: View

    private lateinit var controllerView: View

    private lateinit var controllerMoveBack: View
    private lateinit var controllerPlayPause: ImageView
    private lateinit var controllerMoveForward: View
    private lateinit var controllerCurrentTime: TextView
    private lateinit var controllerSeekbar: MySeekBar
    private lateinit var controllerDuration: TextView


    private val videoList = ArrayList<Video>()
    private val adapter = VideoListAdapter()

    private val handler = object :Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)

            setPlayUi()


            sendEmptyMessageDelayed(0, 1000)
        }
    }

    @SuppressLint("UnsafeOptInUsageError")
    override fun onCreate(savedInstanceState: Bundle?) {
        //设置全屏
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)


        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_video_list)


        statusBarBg = findViewById(R.id.status_bg)


        playerView = findViewById(R.id.player_view)
        exoPlayer = ExoPlayer.Builder(
            this,
            DefaultRenderersFactory(this).setMediaCodecSelector(BlackListMediaCodecSelector()),
            DefaultMediaSourceFactory(this)
        ).build()
        playerView.player = exoPlayer

        exoPlayer?.addListener(object :Listener{
            override fun onPlaybackStateChanged(playbackState: Int) {
                super.onPlaybackStateChanged(playbackState)
                if (playbackState == Player.STATE_ENDED) {
                    controllerPlayPause.isSelected = false
                    controllerPlayPause.setImageResource(android.R.drawable.ic_media_play)
                } else if (playbackState == Player.STATE_READY) {
                    if (exoPlayer?.isPlaying == false) {
                        exoPlayer?.play()
                    }

                    controllerPlayPause.isSelected = true
                    controllerPlayPause.setImageResource(android.R.drawable.ic_media_pause)
                    setPlayUi()
                }
            }
        })

        exoPlayer?.playWhenReady = true;
        playerView.hideController()
        playerView.controllerAutoShow = false

        //exoPlayer?.setMediaItem(MediaItem.fromUri(Uri.parse("http://10.114.38.226:8090/files/zeekrvideo2od_vp9.webm")))
        //exoPlayer?.prepare()





        findViewById<RecyclerView>(R.id.video_list).adapter = adapter

        controllerView = findViewById(R.id.video_view_controller)

        controllerMoveBack = findViewById(R.id.video_play_move_backward)
        controllerPlayPause = findViewById(R.id.video_play_pause)
        controllerMoveForward = findViewById(R.id.video_play_move_forward)
        controllerCurrentTime = findViewById(R.id.video_controller_current_time)
        controllerSeekbar = findViewById(R.id.video_controller_seekbar)
        controllerDuration = findViewById(R.id.video_controller_duration)


        controllerSeekbar.onMySeekBarChangeListener = object : OnMySeekBarChangeListener {
            override fun onProgressChanged(progress: Float) {
                exoPlayer?.seekTo((progress).toLong())
            }

            override fun onProgressChanging(progress: Float) {}
        }


        findViewById<View>(R.id.video_click_view).setOnClickListener {
            if (controllerView.visibility == View.VISIBLE) {
                controllerView.visibility = View.GONE

                if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    val decorView = window.decorView
                    val uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN
                    decorView.systemUiVisibility = uiOptions
                }
            } else {
                controllerView.visibility = View.VISIBLE

                if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    val decorView = window.decorView
                    val uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    decorView.systemUiVisibility = uiOptions
                }
            }
        }


        controllerPlayPause.setOnClickListener {
            if (it.isSelected) {
                exoPlayer?.pause()
                it.isSelected = false

                handler.removeMessages(0)

                controllerPlayPause.setImageResource(android.R.drawable.ic_media_play)

            } else {
                if (exoPlayer?.playbackState == Player.STATE_ENDED) {
                    exoPlayer?.seekTo(0L)
                } else {
                    exoPlayer?.play()
                }

                it.isSelected = true
                setPlayUi()

                controllerPlayPause.setImageResource(android.R.drawable.ic_media_pause)
            }
        }

        statusBarBg.layoutParams.height = getStatusBarHeight()

        if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            // 横屏状态
            playerView.updateLayoutParams<MarginLayoutParams> {
                width = resources.displayMetrics.widthPixels
                height = (resources.displayMetrics.heightPixels)
            }
            statusBarBg.visibility = View.GONE
        } else if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
            // 竖屏状态
            playerView.updateLayoutParams<MarginLayoutParams> {
                width = resources.displayMetrics.widthPixels
                height = (resources.displayMetrics.widthPixels * 0.5625).toInt()
            }

            statusBarBg.visibility = View.VISIBLE
        }


        getVideoList()
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            // 横屏状态
            playerView.updateLayoutParams<MarginLayoutParams> {
                width = 2400
                height = 1080
                topMargin = 0
            }

            statusBarBg.visibility = View.GONE
        } else if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
            // 竖屏状态
            playerView.updateLayoutParams<MarginLayoutParams> {
                width = resources.displayMetrics.widthPixels
                height = (resources.displayMetrics.widthPixels * 0.5625).toInt()
            }

            statusBarBg.visibility = View.VISIBLE


            val decorView = window.decorView
            val uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            decorView.systemUiVisibility = uiOptions
        }
    }

    override fun onClick(v: View?) {
        playVideo(v?.tag as Video)
    }

    private fun playVideo(video: Video) {
        exoPlayer!!.setMediaItem(MediaItem.Builder().setUri(ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, video.id)).build())

        exoPlayer!!.prepare()
    }

    private fun setPlayUi() {
        controllerSeekbar.max = (((exoPlayer?.duration?:0)).toFloat())
        controllerSeekbar.progress = ((exoPlayer?.currentPosition ?:0)).toFloat()

        controllerDuration.text = CommonUtils.formatMediaPlayTime(((exoPlayer?.duration?:0) / 1000).toInt())

        controllerCurrentTime.text = CommonUtils.formatMediaPlayTime(((exoPlayer?.currentPosition ?:0) / 1000).toInt())

        handler.removeMessages(0)
        handler.sendEmptyMessageDelayed(0, 1000)
    }

    private fun getStatusBarHeight(): Int {
        var result = 0
        val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            result = resources.getDimensionPixelSize(resourceId)
        }
        return result
    }

    override fun onResume() {
        super.onResume()
        exoPlayer?.play()
    }

    override fun onStop() {
        super.onStop()
        exoPlayer?.pause()
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeMessages(0)

        exoPlayer?.release()
    }

    private fun getVideoList() {
        //val videoList: MutableList<Video> = ArrayList()

        // 定义要查询的列
        val projection = arrayOf(
            MediaStore.Video.Media._ID,
            MediaStore.Video.Media.DISPLAY_NAME,
            MediaStore.Video.Media.DURATION,
            MediaStore.Video.Media.SIZE
        )
        contentResolver.query(
            MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
            projection,
            null,
            null,
            null).use { cursor ->

            // 获取列的索引
            val idColumn = cursor!!.getColumnIndexOrThrow(MediaStore.Video.Media._ID)
            val nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME)
            val durationColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION)
            val sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE)
            while (cursor.moveToNext()) {
                // 获取视频的属性
                val id = cursor.getLong(idColumn)
                val name = cursor.getString(nameColumn)
                val duration = cursor.getInt(durationColumn)
                val size = cursor.getInt(sizeColumn)

                // 构造并添加视频对象
                val video = Video(id, duration, size)
                video.name = name
                if (!name.endsWith(".ts")) {
                    if (name.contains("电影") || name.contains("小品") || name.contains("相声"))
                        videoList.add(0, video)
                    else
                        videoList.add(video)
                }
            }
        }

        videoList.sort()
        adapter.notifyDataSetChanged()
    }


    class Video    // getter 和 setter 省略
        (var id: Long, var duration: Int, var size: Int): Comparable<Video> {
        private var sortString: String = ""
        private var sortChar: Char = ' '
        var name: String = ""
            set(value) {
                field = value


                if (TextPinyinUtil.isChinaChar(name[0])) {
                    sortString = TextPinyinUtil.getInstance().convert(name[0] + "")
                        .uppercase(Locale.getDefault()) + if (name.length > 1) (if (TextPinyinUtil.getInstance()
                            .convert(name[1].toString() + "") == null) "" else TextPinyinUtil.getInstance()
                        .convert(name[1].toString() + "")).uppercase(Locale.getDefault()) else ""
                    sortChar = sortString[0]
                } else if (name[0].code in 65..90 || name[0].code in 97..122) { //'A'-'Z' 'a'-'z'
                    sortString = name.uppercase(Locale.getDefault())
                    sortChar = if (name[0].code >= 97) (name[0].code - 32).toChar() else name[0]
                } else {
                    sortChar = '#'
                    sortString = name
                }
            }
        override fun compareTo(other: Video): Int {
            return sortChar.compareTo(other.sortChar)
        }

    }


    inner class VideoListAdapter : Adapter<VideoListHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VideoListHolder {
            val title = TextView(this@VideoListActivity)
            title.setPadding(50, 30, 50, 30)
            title.setOnClickListener(this@VideoListActivity)
            title.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            return VideoListHolder(title)
        }

        override fun getItemCount(): Int {
            return videoList.size
        }

        override fun onBindViewHolder(holder: VideoListHolder, position: Int) {
            holder.item.text = "${position + 1}." + videoList[position].name
            holder.item.tag = videoList[position]
        }
    }

    inner class VideoListHolder(var item: TextView) : ViewHolder(item) {}
}